package com.erainm.dw.hive.udf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.junit.Test;

import java.util.ArrayList;

/**
 * Created by erainm on 2021/9/23 5:01 下午.
 *
 * @Description TODO:解析json串，没有key
 **/
public class ParseJsonArrayWithNoKey extends UDF {
    public ArrayList<String> evaluate(String jsonStr){
        if (Strings.isNullOrEmpty(jsonStr)) {
            return null;
        }
        try {
            JSONArray ob = JSON.parseArray(jsonStr);
            ArrayList<String> result = new ArrayList<>();
            for (Object o : ob) {
                result.add(o.toString());
            }
            return result;
        } catch (JSONException e) {
            return null;
        }
    }

    @Test
    public void JunitJsonArray(){
        String str = "[{\"name\":\"goods_detail_loading\",\"json\":{\"entry\":\"2\",\"goodsid\":\"0\",\"loading_time\":\"11\",\"action\":\"3\",\"staytime\":\"62\",\"showtype\":\"4\"},\"time\":1595298857239},{\"name\":\"notification\",\"json\":{\"action\":\"1\",\"type\":\"1\"},\"time\":1595306400660},{\"name\":\"ad\",\"json\":{\"duration\":\"23\",\"ad_action\":\"0\",\"shop_id\":\"9\",\"event_type\":\"ad\",\"ad_type\":\"3\",\"show_style\":\"0\",\"product_id\":\"22\",\"place\":\"placeindex_right\",\"sort\":\"1\"},\"time\":1595344576673},{\"name\":\"praise\",\"json\":{\"id\":9,\"type\":4,\"add_time\":\"1597834948952\",\"userid\":0,\"target\":1},\"time\":1595321785136}]";
        String key = "ids";
        ArrayList<String> evaluate = evaluate(str);
        System.out.println(evaluate.size());
        System.out.println(JSON.toJSONString(evaluate));
    }
}
